package mn.more.wits.client.util;

import mn.more.wits.client.dto.DataTransferObject;
import mn.more.wits.client.dto.Payload;

/**
 * @author $Author: mikeliucc $
 * @version $Id: ClientModelUtil.java 5 2008-09-01 12:08:42Z mikeliucc $
 */
public final class ClientModelUtil {

	private ClientModelUtil() {}

	public static Payload toPayload(DataTransferObject dto) {
		String encrypted = encrypt(dto.serialize());
		Payload payload = new Payload();
		payload.setData(encrypted);
		return payload;
	}

	public static void toModel(Payload payload, DataTransferObject dto) {
		String decrypted = decrypt(payload.getData());
		dto.deserialize(decrypted);
	}

	private static String encrypt(String decrypted) {
		// todo-mike: crypto breako
		//return toString(Crypto.encrypt(toByteArray(decrypted), toByteArray(AppContext.getHandshake().getKey())));
		return toString(toByteArray(decrypted));
	}

	private static String decrypt(String encrypted) {
		// todo-mike: crypto breako
		//return toString(Crypto.decrypt(toByteArray(encrypted), toByteArray(AppContext.getHandshake().getKey())));
		return toString(toByteArray(encrypted));
	}

	private static byte[] toByteArray(String text) {
		if (text == null || text.length() < 1) { return new byte[0]; }
		char[] charArray = text.toCharArray();
		byte[] byteArray = new byte[charArray.length * 2];
		for (int i = 0; i < charArray.length; i++) {
			char c = charArray[i];
			byteArray[i * 2] = (byte) (c >>> 8);
			byteArray[(i * 2) + 1] = (byte) (c);
		}
		return byteArray;
	}

	private static String toString(byte[] array) {
		if (array == null || array.length < 1) { return ""; }
		char[] chars = new char[array.length / 2];
		for (int i = 0; i < chars.length; i++) {
			chars[i] = (char) (((char) array[i * 2] << 8) + ((byte) array[(i * 2) + 1] & 0xff));
		}

		return new String(chars);
	}
}